package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //提交订单业务
        //判断地址是否超出配速范围，购物车为空，收货地址为空的业务异常情况
        //1.向订单号插入一条记录，并且删除用户购物车数据
        //2.将购物车中的数据插入到订单明细表
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        //查看当前用户下是否有购物车数据如果没有抛出业务异常
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if(shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //构建订单表数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(BaseContext.getCurrentId());
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
        //向订单表插入一条记录
        orderMapper.insert(order);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //将购物车中的数据插入到订单详细表
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        //删除购物车数据
        shoppingCartMapper.delete(BaseContext.getCurrentId());
        //封装返回结果OrderSubmitVo
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(order.getId());
        orderSubmitVO.setOrderNumber(order.getNumber());
        orderSubmitVO.setOrderAmount(order.getAmount());
        orderSubmitVO.setOrderTime(order.getOrderTime());
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
        //支付成功通过websocket向服务端推送信息 包括orderId , type , content
        Map mp = new HashMap();
        mp.put("orderId",orders.getId());
        mp.put("type",1);//1表示来单提醒，2表示催单
        mp.put("content","订单号"+outTradeNo);
        //将mp转为json格式发送到服务端
        String message = JSON.toJSONString(mp);
        webSocketServer.sendToAllClient(message);
    }

    /**
     * 查询历史订单
     * @param
     * @return
     */
    @Override
    public PageResult historyOrder(int page, int pageSize, Integer status) {
       //构建OrdersPageQueryDTO对象
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setPage(page);
        ordersPageQueryDTO.setPageSize(pageSize);
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        //执行分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //得到数据
        Page<Orders> orders = orderMapper.list(ordersPageQueryDTO);
        //封装返回结果
        List<OrderVO> orderVOList = new ArrayList<>();
        if(orders!=null && orders.getTotal()>0){
            orders.forEach(order ->{
                Long orderId = order.getId();
                //根据订单id查询订单详情
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                //封装返回结果
                OrderVO orderVO = new OrderVO();
                orderVO.setOrderDetailList(orderDetails);
                BeanUtils.copyProperties(order,orderVO);
                orderVOList.add(orderVO);
            });
        }
        return new PageResult(orders.getTotal(), orderVOList);
    }

    /**
     * 订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        Orders orders = orderMapper.getById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) throws Exception {
        //取消订单业务逻辑，不应该在订单表以及订单详情表中删除记录
        //应该修改订单状态 如果订单的状态码值超过2则抛出异常表示接单中或者已完成单无法取消订单
        Orders order = orderMapper.getById(id);
        //如果订单为空抛出业务异常
        if(order == null)
        {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果订单状态码大于2则抛出业务异常
        if(order.getStatus() > 2)
        {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(order.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    order.getNumber(), //商户订单号
//                    order.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
//
//            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repeatOrder(Long id) {
        //再来一单业务：
        //1.根据订单id查询订单详情信息
        //2.将订单详情里的菜品或者套餐重新添加到购物车
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);
    }

    /**
     * 服务端订单条件查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //服务端订单搜素业务
        //执行分页得到orders,将orders转换为vo
        //根据orderId得到orderdetail并将orderdetail拼接dishes到vo中
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.list(ordersPageQueryDTO);
        //封装返回结果
        List<OrderVO> orderVOList = getOrderVoList(orders);
        return new PageResult(orders.getTotal(), orderVOList);
    }

    /**
     * 通过orders得到OrderVo列表
     * @param orders
     * @return
     */
    public List<OrderVO> getOrderVoList(Page<Orders> orders){
        List<OrderVO> orderVOList = new ArrayList<>();
          if(orders!=null && orders.getTotal()>0){
              orders.forEach(order->{
                  OrderVO orderVO = new OrderVO();
                  //将公共字段填充到orderVo
                  BeanUtils.copyProperties(order,orderVO);
                  //根据orderId得到orderDetail
                  List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(order.getId());
                  //根据orderDetails拼接成菜品字符串
                  String orderDishes = getOrderDishesStr(orderDetails);
                  orderVO.setOrderDishes(orderDishes);
                  orderVO.setOrderDetailList(orderDetails);
                  orderVOList.add(orderVO);
              });
          }
          return orderVOList;
    }

    /**
     * 根据订单详情得到菜品字符串
     * @param orderDetails
     * @return
     */
    private String getOrderDishesStr(List<OrderDetail> orderDetails) {

        List<String> orderDishList = orderDetails.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());
        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 订单统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //拒单业务，当且仅当订单处于待接单时可以进行退单操作
        //如果订单已经支付，则需要进行退款业务操作
        //根据订单id得到订单信息
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        //判断业务，当前订单是否存在以及当前订单是否处于待接单状态
        if(orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //判断订单是否已经支付
        if(orders.getPayStatus().equals(Orders.PAID))
        {
            log.info("订单已支付，需要进行退款操作");
        }
        //更新订单状态为已取消，以及取消原因，取消时间
        Orders order = new Orders();
        order.setCancelReason(ordersRejectionDTO.getRejectionReason());
        order.setCancelTime(LocalDateTime.now());
        order.setId(ordersRejectionDTO.getId());
        order.setStatus(Orders.CANCELLED);
        orderMapper.update(order);
    }

    /**
     * 商户取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        //商户取消订单业务
        //根据订单id得到订单记录，查看该订单是否已经支付
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        //如果用户已经支付，则进行退款操作
        if(orders == null || !orders.getPayStatus().equals(Orders.PAID)){
            log.info("用户已支付，需要进行退款操作");
        }
        Orders order = new Orders();
        order.setPayStatus(Orders.REFUND);
        order.setId(ordersCancelDTO.getId());
        order.setCancelTime(LocalDateTime.now());
        order.setStatus(Orders.CANCELLED);
        order.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(order);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //派送订单业务：
        //只有订单处于待派送状态才能进行派送处理
        Orders orders = orderMapper.getById(id);
        //判断当前订单状态
        if(orders == null || !orders.getStatus().equals(Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单状态为派送中
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //完成订单业务：只有派送中的订单才能进行订单完成处理
        Orders orders = orderMapper.getById(id);
        if(orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态为已完成
        Orders order = new Orders();
        order.setId(orders.getId());
        order.setStatus(Orders.COMPLETED);
        orderMapper.update(order);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //催单业务：查看订单是否存在，如果不存在抛出业务异常
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_EXIST);
        }
        //利用websocket向服务端推送消息
        Map mp = new HashMap();
        mp.put("type",2);
        mp.put("orderId",id);
        mp.put("content","订单号"+orders.getNumber()+"催单");
        webSocketServer.sendToAllClient(JSONObject.toJSONString(mp));
    }
}
